package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * IoT设备管理Service业务层处理
 *
 * @date 2025-10-28
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据iotId获取IoT设备管理详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo selectDeviceByIotId(String iotId) {

        //1. 先查数据
        Device deviceInDb = lambdaQuery().eq(Device::getIotId, iotId).one();
        //2. 查询平台上的
        if(null != deviceInDb){
            DeviceDetailVo vo = BeanUtil.toBean(deviceInDb, DeviceDetailVo.class);
            // 查询平台上的
            ShowDeviceRequest request = new ShowDeviceRequest();
            request.withDeviceId(iotId);
            try {
                ShowDeviceResponse response = ioTDAClient.showDevice(request);
                //设备的状态
                vo.setDeviceStatus(response.getStatus());
                // 激活时间
                String activeTimeStr = response.getActiveTime();
                //时间的格式2025-10-28T12:48:33.702Z
                System.out.println("activeTime = " + activeTimeStr);
                LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
                activeTime = activeTime.
                        // 这个时间对象当前所在的时区为0时区
                                atZone(ZoneId.from(ZoneOffset.UTC))
                        // 转成上海时区 东8区 +8小时
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                vo.setActiveTime(activeTime);
                return vo;
            } catch (Exception e) {
                log.error("查询Iot平台上的设备{}失败", iotId, e);
            }
        }
        //3. 组装数据并返回
        return null;
    }

    @Override
    public Device selectDeviceById(Long id) {
        return null;
    }

    /**
     * 查询IoT设备管理列表
     * 
     * @param device IoT设备管理
     * @return IoT设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }


    /**
     * 修改IoT设备管理
     * 
     * @param device IoT设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除IoT设备管理
     * 
     * @param ids 需要删除的IoT设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除IoT设备管理信息
     * 
     * @param id IoT设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IoTDAClient ioTDAClient;

    /**
     * 同步IoT平台产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = ioTDAClient.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        //如果有产品数据则存入redis
        if(CollUtil.isNotEmpty( products)){
            redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr( products));
        }
    }

    /**
     * 查询所有的产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> getAllProducts() {
        //1 从redis中查询
        String products = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //2. 转成productVo再返回
        if(StrUtil.isNotEmpty(products)){
            return JSONUtil.toList(products, ProductVo.class);
        }
        return List.of();
    }

    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        //1.查询iot平台上的设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try{
            ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
//            System.out.println(response.toString());
            DeviceShadowProperties reported = response.getShadow().get(0).getReported();
            String reportedTimeStr = reported.getEventTime();
            LocalDateTime reportedTime = LocalDateTimeUtil.parse(reportedTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")).
                        atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) reported.getProperties();
            List<DeviceShadowDataVo> voList = new ArrayList<>();
            properties.forEach((k,v) ->{
                DeviceShadowDataVo vo = new DeviceShadowDataVo();
                vo.setFunctionId(k);
                vo.setValue(String.valueOf(v));
                vo.setEventTime(reportedTime);
                voList.add(vo);
            });
            return voList;
        }catch(Exception e){
            log.error("查询设备影子数据失败",e);
        }
        //转成vo返回
        return List.of();
    }


    /**
     * 新增IoT设备
     *@param dto
     * @return 结果
     */
    @Transactional
    @Override
    public void insertDevice(DeviceDto dto) {
        long count = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if(count > 0){
            throw new RuntimeException("设备名称已存在");
        }
        //设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if(count > 0){
            throw new RuntimeException("设备标识已存在");
        }
        //同一位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .count();
        if(count > 0){
            throw new ServiceException("同一位置已绑定相同产品");
        }

        //保存到数据库
        //生成设备id 生成规则为product_id + _ + node_id拼接而成
        String iotId = dto.getProductKey() + "_" + dto.getNodeId();
        dto.setIotId(iotId);
        //生成密钥
        String secret = UUID.randomUUID().toString().replace("-", "");
        //转成数据对象
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        //是否有门禁,默认为0
        device.setHaveEntranceGuard(0);
        //保存到数据库
        save( device);
        //注册到IoT平台
        registerDevice(dto, secret);
        
    }

    /**
     * 向华为云平台注册设备
     * @param dto
     * @param secret
     */
    private void registerDevice(DeviceDto dto, String secret) {
        AddDeviceRequest request = new AddDeviceRequest();
        //设备本身的信息
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        //生成设备id 生成规则为product_id + _ + node_id拼接而成
        body.withDeviceId(dto.getIotId());
        request.withBody(body);

        AuthInfo authInfo = new AuthInfo();
        //秘钥
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);

        request.withBody( body);
        try {
            AddDeviceResponse response = ioTDAClient.addDevice(request);
            System.out.println("reponse.getDeviceId() = " + response.getDeviceId());
        }catch (Exception e){
            log.error("注册设备失败", e);
            throw new RuntimeException(e);
        }

    }
}
